import P2mLogger from 'p2m-common-logger';
import config from 'config';

import fetch2 from './fetch2';

const logger = new P2mLogger('GET_DEVICE_TOKEN');

const snooze = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

let token: string;

export function getDeviceToken() {
  return token;
}

export function initToken() {
  return start().then((t) => {
    token = t;
    return token;
  });
}

async function start() {
  // waiting for jupiter startup
  const jupiter = true;
  while (jupiter) {
    try {
      const res = await fetch2('<jupiter>/healthcheck', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      if (!res.ok) {
        logger.log('check jupiter service started failed!');
        await snooze(10000);
      }
      logger.log('check jupiter service started success!');
      break;
    } catch (e) {
      logger.log('check jupiter service started failed!');
      await snooze(10000);
    }
  }
  // get token from jupiter
  const jupiterToken = true;
  while (jupiterToken) {
    try {
      const fetchToken = await fetch2('<jupiter>/getToken', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: JSON.stringify({
          apikey: config.get('deviceInfo.apiKey'),
        }),
      });
      if (fetchToken.statusText !== 'OK') {
        logger.log('fetch token from jupiter failed!');
        await snooze(10000);
        return null;
      }
      const tokenJson = await fetchToken.json();
      if (tokenJson.success) {
        logger.log('fetch token from jupiter success!');
        return tokenJson.device_token;
      }
      logger.log(`fetch token from jupiter failed! ${tokenJson.err}`);
      await snooze(10000);
      return null;
    } catch (e) {
      logger.log(`fetch token from jupiter failed! ${e}`);
      await snooze(10000);
    }
  }
}
